package com.myself.controller;

import com.myself.entity.Permission;
import com.myself.entity.Result;
import com.myself.entity.Role;
import com.myself.entity.TreeEntity;
import com.myself.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @Author: Liuzemin
 * @Date: 2020/7/16 8:43
 */
@Controller
@RequestMapping("/roles")
public class RolesController {
    @Autowired
    private RoleService roleService;


    /*查询所有*/
    @RequestMapping("/findAll")
    public String findAll(Model model){
        model.addAttribute("rolesList", roleService.findAll());
        return "page/role";
    }

    /*通过id查询用户*/
    @RequestMapping("/findById")
    @ResponseBody
    public Role findById(@RequestParam("id") Long id){
        try {
            return roleService.findById(id);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /*更新当前角色*/
    @ResponseBody
    @RequestMapping("/update")
    public Result update(@RequestBody Role role){
        try {
            if (role.getDescription() != null){
                roleService.updateUserRole_Id(role);
            }
            roleService.update(role);
            return new Result(true,"更新数据成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "出现未知错误");
        }
    }
    /*删除当前角色*/
    @ResponseBody
    @RequestMapping("/delete")
    public Result delete(@RequestParam("id") Long id){
        try{
            roleService.delete(id);
            return new Result(true, "删除成功");
        }catch (Exception e){
            return new Result(false, "出现未知错误");
        }
    }

    /*创建角色*/
    @ResponseBody
    @RequestMapping("create")
    public Result create(@RequestBody Role role){
        try{
            roleService.create(role);
            return new Result(true, "创建成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "出现未知错误");
        }
    }

    /*更新角色-权限信息*/
    @ResponseBody
    @RequestMapping(value = "/updateRolesPermissions", method = RequestMethod.POST)
    public Result updateRolesPermissions(@RequestBody Map<String, Object> dataMap) {
        try {
            Long id = Long.valueOf((String) dataMap.get("id")); //当前操作角色的id
            ArrayList ids = (ArrayList) dataMap.get("ids"); //当前角色更新的权限id的集合体
            ArrayList parents = (ArrayList) dataMap.get("parents"); //当前更新的角色权限parent信息

            // 更新角色的权限关系即需要维护角色-权限表，前端传来了什么数据？ 1、角色id；2、被选中的权限Id集合。
            // 如何更新角色的权限？我们常会想到，根据表的主键update呀，但是，因为页面上展示的数据是后端构建的ZTree实体类JSON数据，其中并不包含表的主键值
            // 所以，这里就采取一种比较极端的方式，先删除此角色所有关联的权限id，再依次关联此角色当前更新的权限id

            //先删除此角色关联的所有权限id
            roleService.deleteAllRolePermissions(id);

            //再依次关联此角色更新的权限id
            for (int i = 0; i < ids.size(); i++) {
                if (!(boolean) parents.get(i)) {
                    //不是父节点才进行关联，因为父节点是角色，子节点才是权限
                    roleService.correlationPermissions(id, Long.valueOf(String.valueOf(ids.get(i))));
                }
            }
            System.out.println(dataMap);
            return new Result(true, "更新数据成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "发生未知错误");
        }
    }

    /*以JSON格式返回数据库中角色表-权限表的所有数据*/
    @ResponseBody
    @RequestMapping("/getZTreeForRolePermissionAll")
    public List<TreeEntity> getZTreeForRolePermissionAll(@RequestParam("id") Long id) {
        try {
            List<TreeEntity> treeList = new ArrayList<>();
            List<Permission> dataList = roleService.findPermissionByRoleId(id);

            //根据id查询此角色的数据，即为父节点的数据
            Role role = roleService.findById(id);
            treeList.add(new TreeEntity(role.getId(), role.getDescription(), true, role.getPid()));

            //遍历设置子节点数据
            for (Permission permission : dataList) {
                treeList.add(new TreeEntity(permission.getId(), permission.getDescription(), false, permission.getRid()));
            }
            return treeList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*根据角id查询其所关联的权限根据角色id查询当前role-permission表中关联的数据*/
    @ResponseBody
    @RequestMapping("/findPermissionByRoleId")
    public List<Permission> findPermissionByRoleId(@RequestParam("id") Long id) {
        try {
            return roleService.findRolePermissionByRoleId(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加角色 --构建一棵ZTree树
     * <p>
     * 这棵ZTree树仅显示当前角色所关联的权限，不需要得到所有的权限信息
     * <p>
     * 返回的JSON数据结构类似： [{id: xx, name: 父节点, parent: true}, {id: xx, name: 子节点, parent: false}, {子节点...}, {子节点}]
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/getZTreeForAllRoles")
    public List<TreeEntity> getZTreeForAllRoles() {
        try {
            List<TreeEntity> treeList = new ArrayList<TreeEntity>();
            List<Role> dataList = roleService.findAll();

            for (Role role : dataList) {
                if (role.getPid() != null) {
                    if (role.getPid() == 0) {
                        //说明是父节点
                        treeList.add(new TreeEntity(role.getId(), role.getDescription(), true, role.getPid()));
                    } else {
                        //说明是子节点
                        treeList.add(new TreeEntity(role.getId(), role.getDescription(), false, role.getPid()));
                    }
                }
            }
            return treeList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
